package com.devo.icecream.receiver

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.content.getSystemService
import com.devo.icecream.IceCreamApp
import com.devo.icecream.ui.home.HomeActivity
import com.devo.icecream.utils.LIFE_ACTION


class WatchReceiver : BroadcastReceiver() {

    companion object {
        @JvmStatic
        var isStop = false
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if (context == null || intent == null) {
            return
        }

        if (isStop) {
            return
        }
        //接受ActivityWatcherService里面发送过来的广播
        intent.takeIf { it.action == LIFE_ACTION }?.let {
            val manager = context.getSystemService<ActivityManager>()
            val isFront = IceCreamApp.activities.any { it.value == true }
            if (!isFront) {
                manager?.let {
                    val appTask = it.appTasks.firstOrNull {
                        it.taskInfo.baseActivity?.packageName == context.packageName
                    }

                    appTask?.moveToFront() ?: context.startActivity(
                        Intent(
                            context,
                            HomeActivity::class.java
                        ).apply {
                            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        },
                    )
                }
            }

        }
    }
}